package com.cn.longdistancebusstation.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.MainActivity;
import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.base.BaseFragment;
import com.cn.longdistancebusstation.callback.OnCustomViewClickListener;
import com.cn.longdistancebusstation.callback.OnRecyclerViewItemClickListener;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.ListResult;
import com.cn.longdistancebusstation.model.Scenic;
import com.cn.longdistancebusstation.scenic.ScenicDetailsActivity;
import com.cn.longdistancebusstation.scenic.ScenicListActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.squareup.picasso.Picasso;

import org.xutils.common.util.ProcessLock;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by mucheng on 2018/4/12.
 */

public class ScenicFragment extends BaseFragment implements View.OnClickListener,OnRecyclerViewItemClickListener{
    private RecyclerView mSenicRecyclerView;
    private ScenicListAdapter mScenicListAdapter;
    private List<Scenic> mScenicList=new ArrayList<>();
    private TextView mTicketList;
    private OnCustomViewClickListener mOnCustomViewClickListener;
    private String strStart="http";
    private String scenicPath="http://www.12301.cc/";

    private int mCurPage;
    private int mCountPerPage;
    private RefreshLayout mRefreshLayout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.activity_scenic_list,null);
        mSenicRecyclerView=(RecyclerView)view.findViewById(R.id.scenic_list);
        mScenicListAdapter=new ScenicListAdapter();
        mSenicRecyclerView.setAdapter(mScenicListAdapter);
        mSenicRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mScenicListAdapter.setmOnRecyclerViewItemClickListener(ScenicFragment.this);
        //
        initData();
        initView(view);
        //获取景点列表
        getScenic();
        return view;
    }

    private void initData() {
        mCurPage = 0;
        mCountPerPage = 15;
    }


    private void initView(View view){
        //设置下拉刷新，上拉加载更多控价
        mRefreshLayout = (RefreshLayout)view.findViewById(R.id.refreshLayout);
        //设置经典头尾
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(getActivity()));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()));
        //
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mCurPage = 0;
                mScenicList.clear();
                getScenic();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mCurPage++;
                getScenic();
            }
        });
    }
    //    private void refresh() {
//        // 将当前页号设置为1
//        mPageNo=0;
//        getScenic();
//
//    }
//    private void loadingMore() {
//        //页号增加
//        mPageNo++;
//        getScenic();
//    }


    private void getScenic() {
        showHud();
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ListResult<Scenic>> call=httpService.getSenicList(mCurPage*mCountPerPage, mCountPerPage);
        call.enqueue(new Callback<ListResult<Scenic>>() {
            @Override
            public void onResponse(Call<ListResult<Scenic>> call, Response<ListResult<Scenic>> response) {
                hideHud();
                ListResult result=response.body();
                if(result!=null){
                    if(result.getHead().getSuccess()){
                        Gson gson=new Gson();
                        String strBody=gson.toJson(result.getBody().getData());
                        Log.d("数据",strBody);
                        Type type=new TypeToken<List<Scenic>>(){}.getType();
                        ArrayList<Scenic> arrayList = gson.fromJson(strBody, type);
                        mScenicList.addAll(arrayList);
                        Log.d("景点数量", String.valueOf(mScenicList.size()));
                        mScenicListAdapter.notifyDataSetChanged();
                    }

                }else{
                }
                mRefreshLayout.finishRefresh();
                if(mScenicList.size() < mCurPage*mCountPerPage){
                    mRefreshLayout.finishLoadMoreWithNoMoreData();
                }
                else{
                    mRefreshLayout.finishLoadMore();
                }

            }

            @Override
            public void onFailure(Call<ListResult<Scenic>> call, Throwable t) {
                hideHud();
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public void onClick(int position) {
        Intent in=new Intent(getActivity(),ScenicDetailsActivity.class);
        in.putExtra("scenicInfo",mScenicList.get(position));
        startActivity(in);

    }

    @Override
    public void onClickInnerCtrl(int position) {

    }

    @Override
    public void onClickCoupon(int position) {

    }
    @Override
    public void onClickCheckBox(int position) {

    }


    private class ScenicListAdapter extends RecyclerView.Adapter<ScenicViewHolder> {
        private OnRecyclerViewItemClickListener mOnRecyclerViewItemClickListener;
        public void setmOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener mOnRecyclerViewItemClickListener) {
            this.mOnRecyclerViewItemClickListener = mOnRecyclerViewItemClickListener;
        }

        @Override
        public ScenicViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            View view = layoutInflater.inflate(R.layout.scenic_recycle_item, parent, false);
            return new ScenicViewHolder(view);
        }

        @Override
        public void onBindViewHolder(ScenicViewHolder holder, final int position) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mOnRecyclerViewItemClickListener.onClick(position);
                }
            });
            Scenic scenicInfo = mScenicList.get(position);
            holder.bindData(scenicInfo);

        }

        @Override
        public int getItemCount() {
            return mScenicList.size();
        }
    }
    private class ScenicViewHolder extends RecyclerView.ViewHolder {
        private ImageView mScenicImageView;
        private TextView mScenicTitleTextView;
        private TextView mScenicPlaceTextView;
        private TextView mTicketPriceTextView;
        private TextView mSoldAmountTextView;
        public ScenicViewHolder(View itemView) {
            super(itemView);
            mScenicImageView=(ImageView)itemView.findViewById(R.id.imageView_scenic);
            mScenicTitleTextView=(TextView)itemView.findViewById(R.id.textView_scenic_name);
            mScenicPlaceTextView=(TextView)itemView.findViewById(R.id.textView_scenic_place);
            mTicketPriceTextView=(TextView)itemView.findViewById(R.id.textView_scenic_ticket_prices);
            mSoldAmountTextView=(TextView)itemView.findViewById(R.id.textView_sold_amount);
        }
        public void bindData(Scenic scenic){
//            mScenicImageView.setBackground(Drawable.createFromPath((BuildConfig.SERVER_URL+scenic.getUUimgpath())));
            mScenicTitleTextView.setText(scenic.getUUtitle());
            mScenicPlaceTextView.setText(scenic.getUUarea());
            int price=scenic.getBeginPrice();
            mTicketPriceTextView.setText("¥"+price+"起");
            int soldNumber=scenic.getSoldNum();
            mSoldAmountTextView.setText("已售"+soldNumber+"张");
//            Picasso.with(ScenicListActivity.this).load(scenic.getUUimgpath()).into(mScenicImageView);
//            Picasso.with(getActivity()).load(scenic.getUUimgpath()).placeholder(R.mipmap.pre_loading)
//                    .error(R.mipmap.pre_loading).noFade().into(mScenicImageView);
//            Log.d("图片地址",scenic.getUUimgpath());
            if(scenic.getUUimgpath().startsWith(strStart)){
                Picasso.with(getActivity()).load(scenic.getUUimgpath()).placeholder(R.mipmap.pre_loading)
                        .error(R.mipmap.pre_loading).noFade().into(mScenicImageView);
            }else{
                Picasso.with(getActivity()).load(scenicPath+scenic.getUUimgpath()).placeholder(R.mipmap.pre_loading)
                        .error(R.mipmap.pre_loading).noFade().into(mScenicImageView);
                Log.d("图片地址",scenicPath+scenic.getUUimgpath());
            }

        }
    }
    public OnCustomViewClickListener getOnCustomViewClickListener() {
        return mOnCustomViewClickListener;
    }

    public void setOnCustomViewClickListener(OnCustomViewClickListener onCustomViewClickListener) {
        mOnCustomViewClickListener = onCustomViewClickListener;
    }

}
